package com.itbaizhan.itbaizhanlock.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/*
redis的分布式锁
 */
@Component
@Slf4j
public class DistributedRedisLock {
    //redisson的客服端
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 加锁
     * @param lockName
     * @return
     */
    public Boolean lock(String lockName){
        //1.判断redissonClient是否为空
        if(redissonClient == null){
            log.info("DistributedRedisLock redission client is null");
            return false;
        }
        try{
            //2加锁
            RLock lock = redissonClient.getLock("anyLock");
            //3,添加过期时间
            //加锁以后10秒自动解锁，无需调用unlock方法手动解锁
            lock.lock(10, TimeUnit.SECONDS);
            return true;//成功后返回true
        }catch (Exception e){
            e.printStackTrace();
            return false; //失败返回false
        }
    }

    public Boolean unlock(String lockName){
//1.判断redissonClient是否为空
        if(redissonClient == null){
            log.info("DistributedRedisLock redission client is null");
            return false;
        }
        try{
            RLock lock = redissonClient.getLock("anyLock");
            lock.unlock();
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
